import { Router } from '@angular/router';
import { DeviceService } from './../../../@core/services/device.ts/device.service';
import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { PositiondataComponent } from '../../basic-data/storehouse/positiondata/positiondata.component';
import { DeviceCategoryComponent } from '../device-category/device-category.component';
import { EditDeviceCategroyComponent } from '../device-category/edit-device-categroy/edit-device-categroy.component';
@Component({
  selector: 'app-device',
  templateUrl: './device.component.html',
  styleUrls: ['./device.component.scss']
})
export class DeviceComponent {
    pager = {
      total: 20,
      pageIndex: 1,
      pageSize: 20
    };
    model: any =null
    site: any =null
    SearchTerm:string=null;
    pageSizeOptions = [10, 20, 30, 50, 100];
    treeData:any;
    allCheckedStatus = false;
    checkedIds = [];
    deleteIDs = [];
    editemployeeId:""
    msgs: Array<Object> = [];
    option:any;//部门option
    departmentId:any;//部门id
    pathPids=[]//部门树结构路径
    employData:any[]=[];//员工数据
    config = {
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
    }//弹窗配置
    searchequipmentCategoryValue:any=''
    filteredTreeNodes:any
    displayTreeData: any[];
    dataTableOptions = {
      columns: [
        {
          field: 'code',
          header: '设备编码',
          fieldType: 'text',
          fixedLeft:'200px'
        },
        {
          field: 'name',
          header: '设备名称',
          fieldType: 'text',
          fixedLeft:'300px'
        },
        {
          field: 'workCode',
          header: '品牌',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '型号',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '场地',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '购买时间',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '资产编码',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '设备级别',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '创建时间',
          fieldType: 'text'
        },
        {
          field: 'workCode',
          header: '备注',
          fieldType: 'text'
        },
        {
          filed:'enabled',
          header:'状态',
          fieldType:'boolean',
          fixedRight:'0px'
        },
      ]
    };//表头数据
    tableWidthConfig: TableWidthConfig[] = [
      {
        field: 'checkbox',
        width: '80px'
      },
      {
        field:'name',
        width:'120px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'130px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
      {
        field:'name',
        width:'100px'
      },
    ];//表格宽度配置
    selectoptions = [
      '全部','启用','禁用'
    ]
    selectvalue = '全部'
    tabledata = []
    @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
    @ViewChild(DataTableComponent, { static: true }
      ) datatable!: DataTableComponent;//获取table
    displayTableData: any[];
    Status!: string;
    file: any;
    equipmentCategoryId: any;
    constructor(private dialogService: DialogService,private SharedMethodService:SharedMethodService,private StorehouseService:StorehouseService,private DeviceService:DeviceService,private Router:Router){}
    ngOnInit(): void {
      this.DeviceService.GetPagedEquipmentCategoriesWithChildren(1,999).subscribe((data:any)=>{
        this.treeData=data.items
        this.displayTreeData = [{ equipmentCategoryName: '全部',equipmentCategoryId:null}, ...this.treeData];
        this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
        if( this.treeData.length>0){
          this.DeviceService.GetEquipments(null,null,null,null,null,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
            this.tabledata=data.items
            this.displayTableData = this.tabledata;
          })
        }
      })
    }
    afterTreeInit($event: any){
      if($event["null"]){
        $event["null"].data.isActive=true
      }
    }//树形菜单初始化
    getPathPids(node: { equipmentCategoryId: any; subEquipmentCategories: any; }, targetId: any, path = []) {
      if (node.equipmentCategoryId === targetId) {
        return [...path, node.equipmentCategoryId];
      }
      if (node.subEquipmentCategories) {
        for (let subNode of node.subEquipmentCategories) {
          const subPath = this.getPathPids(subNode, targetId, [...path, node.equipmentCategoryId]);
          if (subPath) {
            return subPath;
          }
        }
      }
      return null;
    } //获取树形菜单pid的路径
    nodeSelected($event:any){
      this.option=$event.data.originItem
      this.equipmentCategoryId = $event.data.originItem.equipmentCategoryId;
      this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
            this.displayTableData = this.tabledata;
            this.pager.total=data.totalCount;
          }
        )
          for(let node of  this.treeData){
            const path = this.getPathPids(node, this.equipmentCategoryId);

            if(path){
              this.pathPids = path;
              break;
            }else{
              this.pathPids = []
            }

          }
    }//树形菜单点击事件
    CreatDepartment(dialogtype?: string){
      let data = {
        options: this.treeData,
        pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
        display: false
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '设备类别',
        data:data,
        content: DeviceCategoryComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if(results.modalContentInstance.EquiomentCategory.equipmentCategoryName){
                this.DeviceService.CreateEquiomentCategory(results.modalContentInstance.EquiomentCategory).subscribe((data:any)=>{
                  this.showToast('success','成功','设备类别创建成功')
                  results.modalInstance.hide();
                  this.DeviceService.GetPagedEquipmentCategoriesWithChildren(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                    this.treeData=data.items
                    this.displayTreeData = [{ equipmentCategoryName: '全部',equipmentCategoryId:null}, ...this.treeData];
                    this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                  })
                },(error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                  results.modalInstance.hide();
                })
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }//新建设备类别
    EditDepartment(dialogtype?: string){
      if(this.equipmentCategoryId){
        let data = {
          options: this.treeData,
          pathPids: this.pathPids.slice(0, -1),
          display: false,
          option:this.option
        };
        const results = this.dialogService.open({
          id: 'department',
          ...this.config,
          title: '编辑设备类别',
          data:data,
          content: EditDeviceCategroyComponent,
          dialogtype: dialogtype,
          onClose: () => {
          },
          buttons: [
            {
              cssClass: 'stress',
              text: '确定',
              handler: ($event: Event) => {
                if(results.modalContentInstance.EquiomentCategory.equipmentCategoryName){
                  this.DeviceService.UpdateEquipmentCategory(results.modalContentInstance.EquiomentCategory,data.option.equipmentCategoryId,).subscribe((data:any)=>{
                    this.showToast('success','成功','设备类别编辑成功')
                    results.modalInstance.hide();
                    this.DeviceService.GetPagedEquipmentCategoriesWithChildren(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                      this.treeData=data.items
                      this.displayTreeData = [{ equipmentCategoryName: '全部',equipmentCategoryId:null}, ...this.treeData];
                      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                    })
                  },(error) => {
                    if(error.status==404){
                      this.showToast('error', '失败', '服务器连接失败');
                    }else{
                      this.showToast('error', '失败', error.error);
                    }
                    results.modalInstance.hide();
                  })
                }
                data.display = true;
              },
            },
            {
              id: 'btn-cancel',
              cssClass: 'common',
              text: '取消',
              handler: ($event: Event) => {
                results.modalInstance.hide();
              },
            },
          ],
        });
      }
    }//编辑设备类别
    DeleteDepartment(dialogtype?: string){
      if(this.equipmentCategoryId){
        const results = this.dialogService.open({
          ...this.config,
          title: '删除设备分类',
          content: '确认删除当前选中的设备类目？',
          dialogtype: dialogtype,
          onClose: () => {
          },
          buttons: [
            {
              cssClass: 'stress',
              text: '确定',
              handler: ($event: Event) => {
                this.DeviceService.DeleteEquipmentCategory(this.equipmentCategoryId).subscribe((data:any)=>{
                  this.showToast('success','成功','该设备类别删除成功')
                  results.modalInstance.hide();
                  this.DeviceService.GetPagedEquipmentCategoriesWithChildren(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                    this.treeData=data.items
                    this.displayTreeData = [{ equipmentCategoryName: '全部',equipmentCategoryId:null}, ...this.treeData];
                    this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                  })
                },(error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                  results.modalInstance.hide();
                })
              },
            },
            {
              id: 'btn-cancel',
              cssClass: 'common',
              text: '取消',
              handler: ($event: Event) => {
                results.modalInstance.hide();
              },
            },
          ],
        });
      }
    }//删除设备类别
    showToast(type: any,summary:any,content:any) {
      switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
      }
    }//提示框
    searchWarehouseCategory($event:any){
      this.searchequipmentCategoryValue = $event.target.value;
      if (this.searchequipmentCategoryValue === '') {
        // 如果用户输入的值为空，显示原先的数据
        this.displayTreeData = this.displayTreeData = [{ equipmentCategoryName: '全部',equipmentCategoryId:null}, ...this.treeData];
      } else {
        // 否则，显示过滤后的数据
        this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchequipmentCategoryValue);
        this.displayTreeData = this.filteredTreeNodes;
        this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
      }
    }//搜索设备类目
    pageIndexChange($event: any) {
      this.pager.pageIndex=$event;
      this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
            this.displayTableData = this.tabledata;
            this.pager.total=data.totalCount;
          }
        )
    }//切换页码
    pageSizeChange($event: any){
      this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
            this.displayTableData = this.tabledata;
            this.pager.total=data.totalCount;
          }
        )
    }//改变每页显示数量
    creat(){
      this.Router.navigate(['/pages/device/addDevice'])
    }//新建设备
    delete(id:any,dialogtype?: string ){
      const results = this.dialogService.open({
        id: 'department',
        data: { id: id },
        ...this.config,
        title: '删除仓库',
        content: '确认删除当前选中的设备？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.DeviceService.DeleteEquipment(id).subscribe((data:any)=>{
                this.showToast('success','成功','删除成功')
                results.modalInstance.hide();
                this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items
                      this.displayTableData = this.tabledata;
                      this.pager.total=data.totalCount;
                    }
                  )
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          }
        ],
      });
    }//删除设备
    deltes(dialogtype?: string){
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '删除仓库',
        content: '确认删除当前选中的设备？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.DeviceService.DeleteEquipments(this.checkedIds).subscribe((data:any)=>{
                this.showToast('success','成功','删除成功')
                results.modalInstance.hide();
                this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                  this.tabledata=data.items
                      this.displayTableData = this.tabledata;
                      this.pager.total=data.totalCount;
                    }
                  )
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
              )
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          }
        ],
      });
    }//批量删除
    edit(id:any){
      this.Router.navigate(['/pages/device/editDevice'],{queryParams:{id:id}})
    }//编辑设备
    positionData(rowItem:any,dialogtype?: string){
      let data = {
        rowItem:rowItem,
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        width: '800px',
        title: '仓位信息',
        data:data,
        content: PositiondataComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }//仓位信息
    selctChange(){
      this.Status = this.selectvalue=='全部'?"all":this.selectvalue=='启用'?"enable":"disable"
      setTimeout(() => {
        this.StorehouseService.getWarehouses(this.equipmentCategoryId,this.Status,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
          this.tabledata=data.items;
              this.displayTableData = this.tabledata;
              this.pager.total=data.totalCount;
            })
      }, 100);
    }//下拉框选择
    search(){
      this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
            this.displayTableData = this.tabledata;
            this.pager.total=data.totalCount;
          }
        )
    }//搜索
    reset(){
      this.Status = null
      this.equipmentCategoryId = null
      this.model = ''
      this.SearchTerm = ''
      this.site = ''
      this.DeviceService.GetEquipments(this.equipmentCategoryId,this.Status,this.model,this.site,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
        this.tabledata=data.items
            this.displayTableData = this.tabledata;
            this.pager.total=data.totalCount;
          }
        )
    }//重置
    DownloadModel(){
      this.StorehouseService.downloadWarehouseFileModel().subscribe((data:any)=>{
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '仓库模板.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      })
    }//下载模板
    @ViewChild('fileInput1') fileInput1: any;
    @ViewChild('fileInput2') fileInput2: any;
    onButtonClick() {
      // 当按钮被点击时，触发文件输入的点击事件
      this.fileInput1.nativeElement.click();
    }
    onButtonClick2() {
      // 当按钮被点击时，触发文件输入的点击事件
      this.fileInput2.nativeElement.click();
    }
    importFormExcel(event: any) {
      // 当用户选择了Excel文件时，将其赋值给组件的file属性
      this.file = event.target.files[0];
      this.StorehouseService.importWarehousesFromExcel(this.file).subscribe((data:any)=>{
            this.showToast('success','成功','导入成功')
            this.StorehouseService.getWarehouses(this.equipmentCategoryId,this.Status,this.SearchTerm, this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
              this.tabledata=data.items;
                  this.displayTableData = this.tabledata;
                  this.pager.total=data.totalCount;
                })
          },(error) => {
            if(error.status==404){
              this.showToast('error', '失败', '服务器连接失败');
            }else{
              this.showToast('error', '失败', error.error);
            }
          })
    }
    DownloadWarehouse(){
      // this.StorehouseService.downloadWarehouseFile().subscribe((data:any)=>{
      //   const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      //   const objectUrl = URL.createObjectURL(blob);
      //   const a = document.createElement('a');
      //   document.body.appendChild(a);
      //   a.setAttribute('style', 'display:none');
      //   a.setAttribute('href', objectUrl);
      //   a.setAttribute('download', '仓库信息.xlsx');
      //   a.click();
      //   URL.revokeObjectURL(objectUrl);
      // })
    }//下载设备信息
    onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
      this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
    }
    getCheckedRows() {
      this.SharedMethodService.getCheckedRows(this.datatable,'equipmentId').subscribe((data:any)=>{
        this.deleteIDs=data;
      })
      this.SharedMethodService.getCheckedRows(this.datatable,'equipmentId').subscribe((data:any)=>{
        this.checkedIds=data;
      })
    }//获取选中行
    cleared(){
      this.SharedMethodService.cleared(this.deleteIDs,this.tabledata,this.datatable).subscribe((data:any)=>{
        this.deleteIDs=data;
      })
    }//清空选中行
    DownloadCategoryModel(){
      this.DeviceService.downloadEquipmentCategoryFileModel().subscribe((data:any)=>{
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '设备类别模板.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    )
    }//下载仓库类型模板
    ImportCategory(event: any) {
      // 当用户选择了Excel文件时，将其赋值给组件的file属性
      this.file = event.target.files[0];
      this.StorehouseService.importWarehouseCategoriesFromExcel(this.file).subscribe((data:any)=>{
            this.showToast('success','成功','导入成功')
            this.StorehouseService.getWarehouseCategorysWithChildren(this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
              this.treeData=data.items
              this.displayTreeData = [{ warehouseCategoryName: '全部' ,equipmentCategoryId:null}, ...this.treeData];
              this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
              if( this.treeData.length>0){
                this.StorehouseService.getAllWarehouses().subscribe((data:any)=>{
                  this.tabledata=data.items;
                  this.displayTableData = this.tabledata;
                  this.pager.total=data.totalCount;
                })
              }
            })
          },(error) => {
            if(error.status==404){
              this.showToast('error', '失败', '服务器连接失败');
            }else{
              this.showToast('error', '失败', error.error);
            }
          })
    }
    setOpenTrue = (node: { open: boolean; subEquipmentCategories: any[]; }) => {
      // 为当前节点添加 open: true 属性
      node.open = true;
      // 如果当前节点有子节点，递归处理子节点
      if (Array.isArray(node.subEquipmentCategories)) {
        node.subEquipmentCategories = node.subEquipmentCategories.map(this.setOpenTrue);
      }
      return node;
    }
    filterCategories(categories: any[], keyword: string): any[] {
      const result: any[] = [];
      for (const category of categories) {
        if (category.equipmentCategoryName.includes(keyword)) {
          result.push(category);
          continue;
        }
        if (category.subEquipmentCategories.length > 0) {
          const filteredSubCategories = this.filterCategories(category.subEquipmentCategories, keyword);
          if (filteredSubCategories.length > 0) {
            result.push(...filteredSubCategories);
          }
        }
      }
      return result;
    }
}
